/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Sessions;

import SessionBeans.CartLocal;
import SessionBeans.EuroConvertorLocal;
import entityBeans.*;
import exception.ExceptionCart;
import java.rmi.RemoteException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.CreateException;
import javax.ejb.EJB;
import javax.ejb.SessionContext;
import javax.ejb.Stateful;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.persistence.*;

/**
 *
 * @author BELALOUACHE
 */
@Stateful
public class EcomCustomers implements EcomCustomersRemote {

    private static final String PERSISTENCE_UNIT_NAME = "StoreEcom-ejbPU";
    private EntityManagerFactory factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
    private SessionContext context;
    @EJB
    CartLocal caddie;
    @EJB
    EuroConvertorLocal convertor;
    boolean con = false;
    Customers cust;
    // Add business logic below. (Right-click in editor and choose
    // "Insert Code > Add Business Method")

   /** public EcomCustomers(){
        try {
            this.ejbCreate();
        } catch (CreateException ex) {
            Logger.getLogger(EcomCustomers.class.getName()).log(Level.SEVERE, null, ex);
        }
    }**/
    
    public void ejbCreate() throws CreateException {
        try {
            InitialContext sc = new InitialContext();
            this.caddie = (CartLocal) sc.lookup("java:global/StoreEcom/StoreEcom-ejb/Cart");
            this.convertor = (EuroConvertorLocal) sc.lookup("java:global/StoreEcom/StoreEcom-ejb/EuroConvertor");
        } catch (NamingException ex) {
            Logger.getLogger(EcomCustomers.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    //  @EJB
    @Override
    public CartLocal getCaddie() {
        return caddie;
    }

    //   @EJB
    @Override
    public EuroConvertorLocal getConvertor() {
        return convertor;
    }

    @Override
    public Customers getCustumers() {
        return cust;

    }

    @Override
    public void createCust(Integer id, String name, String fistName, String mail, String pwd, String num_comp, Double solde, String adresse) throws RemoteException {
        EntityManager em = factory.createEntityManager();
        // Begin a new local transaction so that we can persist a new entity
        em.getTransaction().begin();
        //add a new Account
        Accounts cmpClient = new Accounts(num_comp);
        // cmpClient.setIdAccount(num_comp);
        cmpClient.setSolde(solde);
        em.persist(cmpClient);

        // Create a new customers
        Customers client = new Customers(id);
        client.setFistName(fistName);
        client.setName(name);
        client.setMail(mail);
        client.setPwd(pwd);
        client.setAdress(adresse);
        client.setIdAccountFk(cmpClient);
        em.persist(client);
        // Commit the transaction, which will cause the entity to
        // be stored in the database
        System.out.println("Customer was successfully created");

        // It is always good practice to close the EntityManager so that
        // resources are conserved.
        em.close();
        // Connect client
        con = true;
        cust = client;
    }

    @Override
    public void removeCust(Integer idCust) throws RemoteException {
        EntityManager em = factory.createEntityManager();
        // Begin a new local transaction so that we can persist a new entity
        em.getTransaction().begin();
        Customers client = em.find(Customers.class, idCust);
        Accounts cmp = em.find(Accounts.class, client.getIdAccountFk().getIdAccount());
        em.remove(client);
        em.remove(cmp);
        // Commit the transaction, which will cause the entity to
        // be stored in the database
        System.out.println("Your customer was successfully canceled");

        // It is always good practice to close the EntityManager so that
        // resources are conserved.
        em.close();
    }

    @Override
    public void getConnect(String name, String pwd) throws RemoteException {
        EntityManager em = factory.createEntityManager();
        // Begin a new local transaction so that we can persist a new entity
        if (con == true) {
            System.out.println("your are already connected to the system");
        } else {
            em.getTransaction().begin();
            Query q = em.createQuery("SELECT c FROM Customers c WHERE c.name = :name and c.pwd= :pwd");
            q.setParameter("name", name);
            q.setParameter("pwd", pwd);
            cust = (Customers) q.getSingleResult();
            // It is always good practice to close the EntityManager so that
            // resources are conserved.
            em.close();
            con = true;
            System.out.println("Your are connected to the system");
        }
    }

    @Override
    public List<Products> getProducts() throws RemoteException {
        List<Products> lesProd;
        EntityManager em = factory.createEntityManager();
        // Begin a new local transaction so that we can persist a new entity
        em.getTransaction().begin();
        Query q = em.createQuery("SELECT p FROM Products p");
        lesProd = q.getResultList();
        // It is always good practice to close the EntityManager so that
        // resources are conserved.
        em.close();
        return lesProd;
    }

    @Override
    public List<Products> getProdByName(String nameProd) throws RemoteException {
        List<Products> lesProd;
        EntityManager em = factory.createEntityManager();
        // Begin a new local transaction so that we can persist a new entity
        em.getTransaction().begin();
        Query q = em.createQuery("SELECT p FROM Products p WHERE p.nameProd = :nameProd");
        q.setParameter("nameProd", nameProd);
        lesProd = q.getResultList();
        // It is always good practice to close the EntityManager so that
        // resources are conserved.
        em.close();
        return lesProd;
    }

    @Override
    public List<Products> getProdByNameLike(String nameProd) throws RemoteException {
        List<Products> lesProd;
        EntityManager em = factory.createEntityManager();
        // Begin a new local transaction so that we can persist a new entity
        em.getTransaction().begin();
        Query q = em.createQuery("SELECT p FROM Products p WHERE p.nameProd LIKE:nameProd");
        q.setParameter("nameProd", nameProd);
        lesProd = q.getResultList();
        // It is always good practice to close the EntityManager so that
        // resources are conserved.
        em.close();
        return lesProd;
    }

    @Override
    public List<Products> getProdByPrice(Double price) throws RemoteException {
        List<Products> lesProd;
        EntityManager em = factory.createEntityManager();
        // Begin a new local transaction so that we can persist a new entity
        em.getTransaction().begin();
        Query q = em.createQuery("SELECT p FROM Products p WHERE p.priceProd < :priceProd");
        q.setParameter("priceProd", price);
        lesProd = q.getResultList();
        // It is always good practice to close the EntityManager so that
        // resources are conserved.
        em.close();
        return lesProd;
    }

    @Override
    public List<Products> getProdByInterPrice(Double priceInf, Double princeSup) throws RemoteException {
        List<Products> lesProd;
        EntityManager em = factory.createEntityManager();
        // Begin a new local transaction so that we can persist a new entity
        em.getTransaction().begin();
        Query q = em.createQuery("SELECT p FROM Products p WHERE p.priceProd >:priceProd OR p.priceProd <:priceProd");
        q.setParameter("priceProd", priceInf);
        q.setParameter("priceProd", princeSup);
        lesProd = q.getResultList();
        // It is always good practice to close the EntityManager so that
        // resources are conserved.
        em.close();
        return lesProd;
    }

    @Override
    public List<Products> getCart() throws RemoteException {
        return caddie.getLesProduits();
    }

    @Override
    public void addCart(Integer refProd) throws RemoteException {
        caddie.addProduct(refProd);
//        System.out.println("Your product was successfully added");

    }

    @Override
    public void removeCart(Integer refProd) throws RemoteException {
        caddie.removeProduct(refProd);
        //      System.out.println("Your product was successfully removed");

    }

    @Override
    public void byuCart(String AccountCust) throws RemoteException {
        try {
            if (con==false) {
                throw new ExceptionCart();
            }
            caddie.buy(AccountCust);
        } catch (ExceptionCart e) {
            e.getmessage5();
        }

    }

    @Override
    public void CartClear() throws RemoteException {
        caddie.clear();

    }

    @Override
    public List<Productsstore> getStores() throws RemoteException {
        List<Productsstore> lesStores;
        EntityManager em = factory.createEntityManager();
        // Begin a new local transaction so that we can persist a new entity
        em.getTransaction().begin();
        Query q = em.createQuery("SELECT p FROM Productsstore p");
        lesStores = q.getResultList();
        // It is always good practice to close the EntityManager so that
        // resources are conserved.
        em.close();
        return lesStores;
    }

    @Override
    public Double totalCart() throws RemoteException {
        return caddie.getTotalPrice();
    }

    @Override
    public Object getPrimaryKey() throws RemoteException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public Category getCat(int idCat) {
        Category cat;
        EntityManager em = factory.createEntityManager();
        // Begin a new local transaction so that we can persist a new entity
        em.getTransaction().begin();
        cat = em.find(Category.class, idCat);
        // It is always good practice to close the EntityManager so that
        // resources are conserved.
        em.close();
        return cat;
    }

    @Override
    public Productsstore getStore(int idStore) throws RemoteException {
        Productsstore store;
        EntityManager em = factory.createEntityManager();
        // Begin a new local transaction so that we can persist a new entity
        em.getTransaction().begin();
        Query q = em.createQuery("SELECT p FROM Productsstore p WHERE p.referenceStore = :referenceStore");
        q.setParameter("referenceStore", idStore);
        store = (Productsstore) q.getSingleResult();
        // It is always good practice to close the EntityManager so that
        // resources are conserved.
        em.close();
        return store;
    }

    @Override
    public List<Products> getProdByCat(int idCat) throws RemoteException {
        List<Products> lesProd;
        EntityManager em = factory.createEntityManager();
        // Begin a new local transaction so that we can persist a new entity
        em.getTransaction().begin();
        Category cat=em.find(entityBeans.Category.class, idCat);
        Query q = em.createQuery("SELECT p FROM Products p WHERE p.idCategoryFk = :idCategoryFk");
        q.setParameter("idCategoryFk", cat);
        lesProd = q.getResultList();
        // It is always good practice to close the EntityManager so that
        // resources are conserved.
        em.close();
        return lesProd;
    }

    @Override
    public List<Category> getAllCat() {
        List<Category> lesCat;
        EntityManager em = factory.createEntityManager();
        // Begin a new local transaction so that we can persist a new entity
        em.getTransaction().begin();
        Query q = em.createQuery("SELECT c FROM Category c");
        lesCat = q.getResultList();
        // It is always good practice to close the EntityManager so that
        // resources are conserved.
        em.close();
        return lesCat;
    }

    @Override
    public Products getProdById(int idProd) throws RemoteException {
        Products prod;
        EntityManager em = factory.createEntityManager();
        // Begin a new local transaction so that we can persist a new entity
        em.getTransaction().begin();
        prod = em.find(entityBeans.Products.class, idProd);
        // It is always good practice to close the EntityManager so that
        // resources are conserved.
        em.close();
        return prod;
    }

    @Override
    public List<Products> getProductsStore(Integer refStore) throws RemoteException {
        List<Products> lesProd;
        EntityManager em = factory.createEntityManager();
        // Begin a new local transaction so that we can persist a new entity
        em.getTransaction().begin();
        Productsstore store=em.find(entityBeans.Productsstore.class, refStore);
        Query q = em.createQuery("SELECT p FROM Products p WHERE p.idProductsstoreFk=:idProductsstoreFk");
        q.setParameter("idProductsstoreFk", store);
        lesProd = q.getResultList();
        // It is always good practice to close the EntityManager so that
        // resources are conserved.
        em.close();
        return lesProd;
    }

    @Override
    public Double getConverToEuro(Double amount, String curreny) {
        return convertor.convertToEuro(amount, curreny);

    }

    @Override
    public Double getConverFromEuro(Double amout, String currency) {
        return convertor.convertFronEuro(amout, currency);
    }

 
    
}